package homework.sort;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortReducer extends Reducer<LongWritable, Text, LongWritable, Text> {


    LongWritable k=new LongWritable();
    Text v=new Text();

    @Override
    protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {


        // 由于Collection.sort()要接受list，这里自定义list
        List<Long> list=new ArrayList<>();
        for (Text value : values) {
            list.add(Long.parseLong(value.toString()));
        }

        // 执行排序，默认正序
        Collections.sort(list);

        // 自定义排序序号
        int sortNum=1;
        for (Long number : list) {

            k.set(sortNum++);
            // 这里要求输出key + 制表符 +value
            v.set("\t"+number.toString());
            context.write(k,v);
        }

    }
}
